import { defineStore } from 'pinia';
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export const useUserStore = defineStore('user', () => {
     const islogin = ref(false);
     const user = ref({
        userId: null,
        username: null,
    });
    const isneedlogin = async () => {
        if (islogin.value === false) {
            try {
                await ElMessageBox.confirm('请先登录', '登录提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                });
                return false;
            } catch (error) {
                return false;
            }
        }else{
            return true;
        }
    };
    // 退出登录方法，可根据需求添加
    const logout = () => {
        // 1. 重置用户信息
        user.value.userId = null;
        user.value.username = null;
        islogin.value = false;

        // 2. 清空对话相关状态
        conversations.value = {
            id: null,
            userId: null,
            title: '',
            createdTime: null,
        };
        historyConversations.value = [];
        currentConversation.value = {
            conversationId: null,
        };

        // 3. 清空消息相关状态
        messages.value = {
            id: null,
            conversationId: null,
            sender: null,
            text: null,
            fileName: null,
            fileUrl: null,
        };
        historyMessages.value = [];

        // 4. 重置创建对话的开关状态
        canCreateConversation.value = true;

        // 5. 提示并刷新页面
        ElMessage.success('退出登录成功');
        setTimeout(() => {
            window.location.reload(true);
        });
    };

    const canCreateConversation=ref(true);
    const newConversation = async (userId, title) => {
        if (canCreateConversation.value === true) {
            const response = await axios.post('ai/conversations/newConversation', {
                title: title,
                userId: userId,
            })
            if (response.data.code === 200) {
                canCreateConversation.value = false;
                console.log("新建对话，标题为:"+title);
            }else{
                await ElMessageBox.confirm('系统异常，请稍后再试', '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                });
            }
        }
    }
    // 在 store 中修改这部分
    const conversations = ref({
        id: null,
        userId: null,
        title: '',
        createdTime: null,
    });
    const historyConversations = ref([]);

// 完善 getHistoryConversation 方法的错误处理
    const getHistoryConversation = async () => {
        if (!user.value.userId) {
            console.error('用户ID不存在，无法获取历史对话');
            return;
        }
        try {
            const response = await axios.get('ai/conversations/getHistory', {
                params: {
                    userId: user.value.userId,
                }
            });
            if (response.data.code === 200) {
                historyConversations.value = response.data.data || [];
            } else {
                ElMessage.error('获取历史对话失败: ' + (response.data.message || '未知错误'));
            }
        } catch (error) {
            console.error('获取历史对话出错:', error);
            ElMessage.error('网络错误，无法获取历史对话');
        }
        console.log(historyConversations.value);
    }

    const messages = ref({
        id: null,
        conversationId: null,
        sender: null,
        text: null,
        fileName: null,
        fileUrl: null,
    });
    const historyMessages = ref([]);
    const currentConversation = ref({
        conversationId: null,
    })
    const getHistoryMessage = async () => {
        if (!currentConversation.value.conversationId) {
            console.error('对话ID不存在，无法获取历史对话');
            return;
        }
        try {
            const response = await axios.get('ai/messages/getHistory', {
                params: {
                   conversationId: currentConversation.value.conversationId,
                }
            });
            if (response.data.code === 200) {
                historyMessages.value = response.data.data || [];
            } else {
                ElMessage.error('获取历史对话失败: ' + (response.data.message || '未知错误'));
            }
        } catch (error) {
            console.error('获取历史对话出错:', error);
            ElMessage.error('网络错误，无法获取历史对话');
        }
        console.log(historyMessages.value);
    }
    const setCurrentConversation = (conversation) => {
        currentConversation.value.conversationId = conversation.id;
        // 切换对话后立即获取该对话的历史消息
         getHistoryMessage().then(r => null);
    }
    return {
        islogin,
        user,
        setCurrentConversation,
        isneedlogin,
        logout,
        canCreateConversation,
        newConversation,
        conversations,
        historyConversations,
        getHistoryConversation,
        messages,
        currentConversation,
        historyMessages,
        getHistoryMessage,
    };
});